const express = require('express');
const { User } = require('../models');
const { NotFound, BadRequest } = require('http-errors');
const { failure, success } = require('../utils/responses');
const router = express.Router();
const bcrypt = require('bcryptjs');
/* 
查询用户详情
GET /users/me */
router.get('/me', async function (req, res) {
  try {
    const user = await getUser(req);
    success(res, '查询用户成功', { user });
  } catch (error) {
    failure(res, error);
  }
});

/* 
更新用户信息
GET /users/account */
router.get('/account', async function (req, res) {
  try {
    const body = {
      email: req.body.email,
      username: req.body.username,
      current_password: req.body.current_password,
      password: req.body.password,
      passwordConfirmation: req.body.passwordConfirmation,
    };
    if (!body.current_password) {
      throw new BadRequest('当前密码必须填写');
    }
    if (body.password !== body.passwordConfirmation) {
      throw new BadRequest('两次密码不一致');
    }
    const user = await getUser(req, true);
    const isPasswordValid = bcrypt.compareSync(body.current_password, user.password);
    if (!isPasswordValid) {
      throw new BadRequest('当前密码不正确');
    }
    await user.update(body);
    delete user.dataValues.password;
    success(res, '更新成功', { user });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法:查询当前用户
 * */

const getUser = async (req, showPassword = false) => {
  const id = req.userId;
  let condition = {};
  if (!showPassword) {
    condition = {
      attributes: { exclude: ['password'] },
    };
  }
  const user = await User.findByPk(id, condition);
  if (!user) {
    throw new NotFound(`Id: ${id}用户未注册`);
  }
  return user;
};
module.exports = router;
